package com.admin.action;

import java.io.File;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.util.StringUtils;

import com.cheers.action.BaseAction;
import com.cheers.common.Constants;
import com.cheers.common.ResultModel;
import com.cheers.model.Product;
import com.cheers.service.ProductService;
import com.cheers.util.VerifyUtil;


public class ManageProductAction extends BaseAction {

	private static final long serialVersionUID = -6833789286367120856L;
	
	@Resource
	private ProductService productService;
	
	private String title;
	private String price;
	private File photo;
	private String describe;
	private String point;
	
	
	public String add() throws Exception {
		//验证
		if (StringUtils.isEmpty(title)) {
			result = new ResultModel(Constants.NO, "商品名称不能为空", "");
			return SUCCESS;
		}
		if (StringUtils.isEmpty(price)) {
			result = new ResultModel(Constants.NO, "商品价格不能为空", "");
			return SUCCESS;
		}
		if (photo==null || photo.length()==0) {
			result = new ResultModel(Constants.NO, "商品图片不能为空", "");
			return SUCCESS;
		}
		if (StringUtils.isEmpty(point)) {
			result = new ResultModel(Constants.NO, "兑换积分不能为空", "");
			return SUCCESS;
		}
		if (!VerifyUtil.numberTest(price)) {
			result = new ResultModel(Constants.NO, "价格应为正整数", "");
			return SUCCESS;
		}
		if (!VerifyUtil.numberTest(point)) {
			result = new ResultModel(Constants.NO, "兑换积分应为正整数", "");
			return SUCCESS;
		}
		if (!isPost("add")) {
			result = new ResultModel(Constants.NO, Constants.INVALID_DESC, "");
			return SUCCESS;
		}
		
		//构造实体
		double priceDou = Double.parseDouble(price);
		Product product = new Product();
		product.setTitle(title);
		product.setPrice(priceDou);
		//上传图片 
		String picture = upload(photo);
		product.setPicture(picture);
		product.setDepict(describe);
		//使用兑换多少积分
		product.setBuyed(Integer.parseInt(point));
		product.setCtime(new Date());
		
		//添加幸运活动
		try {
			productService.add(product);
		} catch (Exception e) {
			result = new ResultModel(Constants.NO, Constants.NO_DESC, "");
			return SUCCESS;
		}
		result = new ResultModel(Constants.OK, Constants.OK_DESC, "");
		return SUCCESS;
	}
	//上传图片 TODO
	private String upload(File photo) throws Exception {
		return "/images/20140122160014869.jpg";
	}


	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
	public File getPhoto() {
		return photo;
	}
	public void setPhoto(File photo) {
		this.photo = photo;
	}
	public String getDescribe() {
		return describe;
	}
	public void setDescribe(String describe) {
		this.describe = describe;
	}
	public String getPoint() {
		return point;
	}
	public void setPoint(String point) {
		this.point = point;
	}
	
}
